package at.fhj.antesk.steamvaluecalc.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FileHandler {

	private static final String DATA_TXT = "data.txt";
    private static final String LINE_SEPERATOR = System.getProperty("line.separator");
    private static Logger logger = LoggerFactory.getLogger(FileHandler.class);
    private static final String ERROR_WRITING_FILE_APPEND_MODE = "Error writing file (Append mode) ";
    private static final String ERROR_WRITING_FILE_OVERWRITE_MODE = "Error writing file (Overwrite mode) ";

    protected void writeToTextFileAppend(String data, String filepath) throws IOException {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(filepath, true));
            out.write(data);
            out.close();
        } catch (IOException e) {
            logger.debug(ERROR_WRITING_FILE_APPEND_MODE + filepath, e);
            throw  new IOException(ERROR_WRITING_FILE_APPEND_MODE + filepath);
        }
    }
    
    protected void writeToTextFileOverwrite(String data, String filepath) throws IOException {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(filepath, false));
            out.write(data);
            out.close();
        } catch (IOException e) {
			logger.debug(ERROR_WRITING_FILE_OVERWRITE_MODE + filepath, e);
            throw  new IOException(ERROR_WRITING_FILE_OVERWRITE_MODE + filepath);
        }
    }


    protected String readFromTextFile(String filePath) {
        StringBuilder contents = new StringBuilder();
        File aFile = new File(filePath);

        BufferedReader input = null;
        try {
            input = new BufferedReader(new FileReader(aFile));
            while (input.ready()) {
                String line = input.readLine();
                contents.append(line);
                if (input.ready()) {
                    contents.append(LINE_SEPERATOR);
                }

                input.close();
            }
        } catch (FileNotFoundException e) {
            logger.error("file not found: ", e);
        } catch (IOException e) {
            logger.error("error reading or writing file: ", e);
        }

        return contents.toString();
    }

    public void storeData(String data) {
        try {
            writeToTextFileOverwrite(data, DATA_TXT);
        } catch (IOException e) {
            logger.error("Cannot store data into file: " + DATA_TXT, e);
        }
    }

    public String loadData() {
        return readFromTextFile(DATA_TXT);
    }

    public void updateData(String data) {
        logger.warn("updateData(String) Not implemented yet");
    }

}
